package zwp.example.demo1;

import com.example.common.exceptions.BaseException;
import com.example.common.exceptions.CommonException;
import org.junit.jupiter.api.Test;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.concurrent.TimeUnit;

@SpringBootTest
public class Demo8Redisson {
    @Autowired
    private RedissonClient redissonClient;

    @Test
    public void test1() {
        //1.获取锁对象，指定锁名称
        RLock anyLock = redissonClient.getLock("anyLock");
        // 2.尝试获取锁，参数：waitTime、leaseTime、时间单位
        try {
            boolean isSuccess = anyLock.tryLock(1, 10, TimeUnit.SECONDS);

            if (!isSuccess){
                //如果获取失败执行失败操作
                throw new CommonException("获取锁失败！");
            }else {
                //如果获取成功执行任务
                System.out.println("获取锁成功！");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //释放锁
            anyLock.unlock();
        }

    }
}
